#include "StdAfx.h"
#include "JG_FixIDGenerator.h"
#include "JG_Com_CriticalLock.h"
#include "CommonFun.h"

const char* FILE_VIEW_NAME = "IDGenerator";
const char* ID_FILE_NAME   = ".\\Ids.dat";

JG_FixIDGenerator::JG_FixIDGenerator(void)
	:m_pFixIDStore(NULL)
{
	InitializeCriticalSection(&m_csIDGenerator);
}


JG_FixIDGenerator::~JG_FixIDGenerator(void)
{
	if( NULL != m_MapIDStore )
	{
		BOOL bUnViewMap = m_MapIDStore.FreeViewMap(m_pFixIDStore);
		m_pFixIDStore = NULL;
	}

	DeleteCriticalSection(&m_csIDGenerator);
}

int JG_FixIDGenerator::InitIDGenerator()
{
	CString strExeDIR = GetExeDIR();  
	strExeDIR.Remove('\\');
	strExeDIR.Remove(':');
	strExeDIR += FILE_VIEW_NAME;

	int nResult = m_MapIDStore.CreateFileViewMapping(strExeDIR,ID_FILE_NAME,sizeof(struFixIDStore));
	ASSERT(nResult==S_OK);

	m_pFixIDStore = (struFixIDStore*)m_MapIDStore.ViewMap(sizeof(struFixIDStore),0);
	ASSERT(m_pFixIDStore!=NULL);

	if( m_pFixIDStore->iNowDate != GetLocalDate() )
	{
		ZeroMemory(m_pFixIDStore,sizeof(struFixIDStore));
		m_pFixIDStore->iNowDate = GetLocalDate();
	}

#ifdef _DEBUG
	m_pFixIDStore->iExecID++;
#endif // _DEBUG

	return S_OK;
}

void JG_FixIDGenerator::DateCheckup()
{
	int nData = GetLocalDate();

	if( m_pFixIDStore->iNowDate != nData )
	{
		m_pFixIDStore->iNowDate = nData;
		m_pFixIDStore->iOrderID = 0;
		m_pFixIDStore->iExecID  = 0;
	}
}

std::string JG_FixIDGenerator::GenOrderID()
{
	CJGCriticalLock _csOrderID(&m_csIDGenerator);

	DateCheckup();

	if( m_pFixIDStore->iOrderID < 0 )
	{
		m_pFixIDStore->iOrderID = 0;
	}
	else
	{
		m_pFixIDStore->iOrderID ++;
	}

	std::stringstream stream;
	stream <<"O"<<m_pFixIDStore->iOrderID;
	//std::string strOrderID(stream.str());

	return stream.str();
}

std::string JG_FixIDGenerator::GenExecID()
{
	CJGCriticalLock _csExecID(&m_csIDGenerator);

	DateCheckup();

	if( m_pFixIDStore->iExecID < 0 )
	{
		m_pFixIDStore->iExecID = 0;
	}
	else
	{
		m_pFixIDStore->iExecID++;
	}

	std::stringstream stream;
	stream <<"E"<< m_pFixIDStore->iExecID;
	//std::string strExecID(stream.str());

	return stream.str();
}

